package platformlog_logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateClusterInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateClusterInfoLogic 更新集群信息
func NewUpdateClusterInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateClusterInfoLogic {
	return &UpdateClusterInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateClusterInfoLogic) UpdateClusterInfo(req *types.UpdateClusterInfoRequest) (resp *types.ClusterInfoResponse, err error) {
	var tableName string
	if l.svcCtx.Config.UseMysql {
		tableName = l.svcCtx.Config.Mysql.Tables.ClusterInfo
	} else {
		tableName = l.svcCtx.Config.SQLite.Tables.ClusterInfo
	}

	updateSQL := fmt.Sprintf(`
        UPDATE %s 
        SET cluster_name = ?, node_count = ?, cluster_version = ?, status = ?, description = ?, owner = ?, region = ?
        WHERE cluster_id = ?`, tableName)

	checkExistSQL := fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE cluster_id = ?)`, tableName)

	err = l.svcCtx.Conn.Transact(func(session sqlx.Session) error {
		// 先检查cluster_id是否存在
		var exists bool
		err := session.QueryRow(&exists, checkExistSQL, req.ClusterInfo.ClusterID)
		if err != nil {
			return fmt.Errorf("检查cluster_id存在性失败: %w", err)
		}
		if !exists {
			return fmt.Errorf("cluster_id不存在: %s", req.ClusterInfo.ClusterID)
		}

		// 更新cluster_info记录
		_, err = session.Exec(updateSQL,
			req.ClusterInfo.ClusterName, req.ClusterInfo.NodeCount, req.ClusterInfo.ClusterVersion, req.ClusterInfo.Status, req.ClusterInfo.Description, req.ClusterInfo.Owner, req.ClusterInfo.Region, req.ClusterInfo.ClusterID)
		if err != nil {
			return fmt.Errorf("更新cluster_info失败: %w", err)
		}
		return nil
	})

	if err != nil {
		return &types.ClusterInfoResponse{
			Code:    500,
			Message: fmt.Sprintf("集群信息更新失败: %v", err),
			Data:    []types.ClusterInfo{},
		}, err
	}

	// 返回成功的响应
	return &types.ClusterInfoResponse{
		Code:    200,
		Message: "集群信息更新成功",
		Data:    []types.ClusterInfo{req.ClusterInfo},
	}, nil
}
